package com.hwadee.teachingprocessmanagementsystem.interceptor;

import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.hwadee.teachingprocessmanagementsystem.annotation.Role;
import com.hwadee.teachingprocessmanagementsystem.annotation.RoleAuthorizationAnnotation;
import com.hwadee.teachingprocessmanagementsystem.service.base.RedisService;
import com.hwadee.teachingprocessmanagementsystem.util.ColorLoggerUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Objects;

import static com.hwadee.teachingprocessmanagementsystem.util.JWTUtils.verify;

/**
 * @Description: JWT拦截器
 * @Author: Jukomu
 * @Package: com.hwadee.teachingprocessmanagementsystem.interceptor
 * @Project: MyPetStore-SSM
 * @name: JWTInterceptor
 * @Date: 2024/4/1 1:48
 * @Filename: JWTInterceptor
 */
@Component
public class JWTInterceptor implements HandlerInterceptor {
    private final ColorLoggerUtils logger = ColorLoggerUtils.getLogger(JWTInterceptor.class);
    @Autowired
    private RedisService redisService;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (Objects.equals(request.getMethod(), "OPTIONS")) {
            logger.info("OPTIONS");
            return true;
        }
        RoleAuthorizationAnnotation roleAuthorizationAnnotation = null;
        if (handler instanceof HandlerMethod handlerMethod) {
            roleAuthorizationAnnotation = AnnotationUtils.findAnnotation(handlerMethod.getMethod(), RoleAuthorizationAnnotation.class);
        }
        // 处理不是 HandlerMethod 类型的情况
        if (roleAuthorizationAnnotation == null) {
            logger.info("Role authorization:common");
            return true;
        }
        // 从请求头中获取令牌
        Object token = request.getHeader("Token");
//        if (token == null) {
//            token = request.getParameter("token");
//        }

        if (token == null) {
            logger.info("Get Token:No token");
            return false;
        }

        logger.info("Get Token:" + token);

        // 验证Redis中的缓存
        Object cacheValue = redisService.getCacheValue(String.valueOf(token));
        if (cacheValue == null) {
            logger.info("Role authorization:Token is out of date");
            return false;
        }

        if (roleAuthorizationAnnotation.value() == Role.MANAGER) {
            try {
                DecodedJWT decodedJWT = verify((String) token);
                if (decodedJWT.getClaim("role").asString().equals("MANAGER")) {
                    // token有效且权限为管理员
                    logger.info("Role authorization:{manager:"+decodedJWT.getClaim("uid").asString()+"}");
                    return true;
                } else {
                    // token有效但权限不是管理员
                    logger.warn("Role authorization failed:manager");
                    return false;
                }
            } catch (JWTVerificationException e) {
                // token无效
                logger.info("Role authorization:Token is invalid");
                return false;
            }
        }
        if (roleAuthorizationAnnotation.value() == Role.USER) {
            try {
                DecodedJWT decodedJWT = verify((String) token);
                // 只要令牌有效都满足USER权限
                logger.info("Role authorization:{user:"+decodedJWT.getClaim("uid").asString()+"}");
                return true;
            } catch (JWTVerificationException e) {
                // token无效
                logger.info("Role authorization:Token is invalid");
                return false;
            }
        }
        return false;
    }
}
